<template>
  <div class="container">
    <van-search
      v-model="value"
      show-action
      placeholder="请输入用户名"
      @search="onSearch"
      @cancel="router.go(-1)"
      shape="round"
    />
    <div v-if="form">
      <div class="container pt-4 pb-4">
        <van-form @submit="onSubmit" ref="formInstance" :disabled="disabled">
          <van-cell-group inset>
            <van-field
              v-model="form.policeName"
              name="policeName"
              label="姓名"
              placeholder="请填写姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <van-field
              v-model="form.sex"
              name="sex"
              label="性别"
              placeholder="请选择性别"
              readonly
              @click="onClick('sex')"
              :rules="[{ required: true, message: '请选择性别' }]"
            >
            </van-field>
            <van-field
              v-model="form.birthDay"
              name="birthDay"
              label="出生年月"
              readonly
              placeholder="请选择出生年月"
              @click="onClick('birthDay')"
              :rules="[{ required: true, message: '请选择出生年月' }]"
            />
            <van-field
              v-model="form.mobile"
              name="mobile"
              label="手机号"
              placeholder="请输入手机号"
              :disabled="true"
              :rules="[{ required: true, message: '请输入手机号' }]"
            />
            <van-field
              v-model="form.nation"
              name="nation"
              label="籍贯"
              readonly
              placeholder="请选择籍贯"
              @click="onClick('nation')"
              :rules="[{ required: true, message: '请选择籍贯' }]"
            />
            <van-field
              v-model="form.zoneId"
              name="zoneId"
              label="所属分局"
              readonly
              placeholder="请选择所属分局"
              @click="onClick('zoneId')"
              :rules="[{ required: true, message: '请选择所属分局' }]"
            />
            <van-field
              v-model="form.department"
              name="department"
              label="所属科室"
              placeholder="请输入所属科室"
              :rules="[{ required: true, message: '请输入所属科室' }]"
            />
            <van-field
              v-model="form.joinPoliceTime"
              name="joinPoliceTime"
              label="入警时间	"
              readonly
              placeholder="请选择入警时间	"
              @click="onClick('joinPoliceTime')"
              :rules="[{ required: true, message: '请选择入警时间' }]"
            />
            <van-field
              v-model="form.joinNationTime"
              name="joinNationTime"
              label="入党时间"
              readonly
              placeholder="请选择入党时间"
              @click="onClick('joinNationTime')"
              :rules="[{ required: true, message: '请选择入党时间' }]"
            />
            <van-field
              v-model="form.idPhoto"
              name="idPhoto"
              label="证件照"
              placeholder="请上传证件照"
              readonly
            >
              <template #input>
                <van-uploader
                  :before-read="useCompressor"
                  :disabled="disabled"
                  :max-count="1"
                  multiple
                  v-model="fileList"
                /> </template
            ></van-field>
            <van-field
              v-model="form.photoList"
              name="photoList"
              label="相关照片"
              readonly
              :rules="[{ required: true, message: '请上传相关照片' }]"
            >
              <template #input>
                <van-uploader
                  :before-read="useCompressor"
                  :disabled="disabled"
                  :max-count="5"
                  multiple
                  v-model="fileList1"
                /> </template
            ></van-field>
            <van-field
              v-model="form.jobDesc"
              name="jobDesc"
              label="工作经历"
              placeholder="请填写工作经历"
              type="textarea"
              :rules="[{ required: true, message: '请填写工作经历' }]"
            />
            <van-field
              v-model="form.policeHonor"
              name="policeHonor"
              label="从警荣誉"
              placeholder="请输入从警荣誉"
              type="textarea"
              :rules="[{ required: true, message: '请填写从警荣誉' }]"
            >
            </van-field>
            <van-field
              v-model="form.policeStory"
              name="policeStory"
              label="个人从警故事"
              type="textarea"
              placeholder="请输入个人从警故事"
              :rules="[{ required: true, message: '请填写个人从警故事' }]"
            />
            <van-field
              v-model="form.hobby"
              name="hobby"
              label="业余兴趣爱好"
              type="textarea"
              placeholder="请输入业余兴趣爱好"
              :rules="[{ required: true, message: '请填写业余兴趣爱好' }]"
            />
          </van-cell-group>
          <div style="margin: 16px">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
            >
              {{ isEdit ? "提交" : "编辑" }}
            </van-button>
          </div>
        </van-form>
        <van-popup round v-model:show="showPicker" position="bottom">
          <van-picker
            v-if="
              !['joinNationTime', 'joinPoliceTime', 'birthDay'].includes(
                columnsType
              )
            "
            :columns="columnsValue"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
          <van-date-picker
            v-else
            :minDate="new Date(1980, 0, 1)"
            v-model="currentDate"
            title="选择年月"
            :columns-type="['year', 'month']"
            @confirm="handleConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>
      </div>
    </div>
    <van-empty
      v-else
      image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
      image-size="80"
      description="空"
    />
    <van-dialog
      v-model:show="show"
      title="提示"
      show-cancel-button
      :before-close="beforeClose"
      @open="onOpen"
    >
      <p class="pl-4 mt-2">
        <span v-if="isSend">已发送验证码到:{{ form?.mobile }}</span>
        <span v-else>验证码发送失败</span>
      </p>
      <van-form ref="formInstance1">
        <van-field
          required
          v-model="verify"
          name="verify"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入正确内容' }]"
      /></van-form>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { getList, send, checkSmsCode, updateInfo, upload } from "@/api";
import { useUserInfo } from "@/store";
import { useCompressor } from "@/utils";
import router from "@/router";
import {
  showToast,
  type PickerConfirmEventParams,
  type UploaderFileListItem,
} from "vant";
const value = ref(""),
  form = ref<any>(),
  disabled = ref(true),
  show = ref(false),
  verify = ref("");
const sexOption = [
    {
      value: "男",
      text: "男",
    },
    {
      value: "女",
      text: "女",
    },
  ],
  isSend = ref(false);
const store = useUserInfo();
const fileList = ref([]);
const showPicker = ref(false),
  formInstance = ref(null),
  currentDate = ref(["1980", "01"]),
  fileList1 = ref([]),
  loading = ref(false);
const columnsType = ref(""),
  isEdit = ref(false),
  formInstance1 = ref(null);
const columnsValue = computed(() => {
  return columnsType.value === "sex"
    ? sexOption
    : columnsType.value === "zoneId"
    ? store.options
    : store.provinces.map((item) => ({ text: item, value: item }));
});
const onSubmit = async () => {
    if (isEdit.value) {
      const { photoList, idPhoto, zoneId, mobile, ...req } = form.value;
      loading.value = true;
      const idPhoto1 = fileList.value.filter((item) => item.status === "done").map(item=>item.url);
      const photoList1 = fileList1.value.filter((item) => item.status === "done").map(item=>item.url);
      try {
        for (let p of fileList.value.filter((item) => item.status !== "done")) {
          const data = await upload({ file: p.file });
          idPhoto1.push(data);
        }

        for (let p of fileList1.value.filter(
          (item) => item.status !== "done"
        )) {
          const data = await upload({ file: p.file });
          photoList1.push(data);
        }
      } catch {
        loading.value = false;
      }

      updateInfo({
        ...req,
        zoneId: store.options.find((item) => item.text === zoneId)?.id,
        idPhoto: idPhoto1.join(","),
        photoList: photoList1.join(","),
      })
        .then(() => {
          showToast("操作成功");
          router.push("/result");
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
        });
    } else {
      show.value = true;
    }
  },
  onConfirm = ({ selectedValues }: PickerConfirmEventParams) => {
    form.value[columnsType.value] = selectedValues[0];
    showPicker.value = false;
  },
  onClick = (type) => {
    if (disabled.value) return;
    showPicker.value = true;
    columnsType.value = type;
  },
  handleConfirm = ({ selectedValues }) => {
    form.value[columnsType.value] = selectedValues.join("-");
    currentDate.value = ["1980", "01"];
    showPicker.value = false;
  };
const onSearch = (value: string) => {
    getList({
      policeName: value,
    }).then((res) => {
      const { idPhoto, photoList, zoneId, ...req } = res;
      fileList.value = idPhoto
        .split(",")
        .filter((item) => item)
        .map((item) => {
          return {
            url: item,
            status: "done",
          };
        });
      fileList1.value = photoList
        .split(",")
        .filter((item) => item)
        .map((item) => {
          return {
            url: item,
            status: "done",
          };
        });
      form.value = {
        ...req,
        idPhoto,
        photoList,
        zoneId: store.options.find((item) => item.id === zoneId)?.text,
      };
    });
  },
  beforeClose = async (action: "confirm" | "cancel") => {
    if (action === "confirm") {
      try {
        await formInstance1.value?.validate();
        await checkSmsCode({ id: form.value.id, code: verify.value });
        isEdit.value = true;
        disabled.value = false;
        return true;
      } catch (e) {
        return false;
      }
    } else {
      return true;
    }
  },
  onOpen = () => {
    send({
      id: form.value.id,
    }).then(() => {
      showToast("验证码发送成功");
      isSend.value = true;
    });
  };
</script>

<style lang="scss" scoped>
.container {
  background-color: #f9f9f9;
  height: 100%;
}
</style>
